﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Globalization;
using System.Xml.Linq;

namespace PriceExtractor
{
    class PriceExtractor
    {
        static Dictionary<string, decimal> ExtractPricesXPath(string xmlName, int olderThanYears)
        {
            int currentYear = DateTime.Today.Year;
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlName);
            string xPathQuery = "/catalog/album";
            CultureInfo culture = new CultureInfo("en-US");
            Dictionary<string, decimal> albumPrices = new Dictionary<string, decimal>();
            XmlNodeList albums = doc.SelectNodes(xPathQuery);
            foreach (XmlNode album in albums)
            {
                string yearString = album.SelectSingleNode("year").InnerText;
                int year = int.Parse(yearString);
                if (currentYear - year >= olderThanYears)
                {
                    string albumName = album.SelectSingleNode("name").InnerText;
                    string albumPriceString = album.SelectSingleNode("price").InnerText;
                    decimal albumPrice = decimal.Parse(albumPriceString, culture);
                    albumPrices.Add(albumName, albumPrice);
                }
            }
            return albumPrices;
        }

        static Dictionary<string, decimal> ExtractPricesLINQ(string xmlName, int olderThanYears)
        {
            CultureInfo culture = new CultureInfo("en-US");
            int currentYear = DateTime.Today.Year;
            XDocument doc = XDocument.Load(xmlName);
            var albums = from album in doc.Descendants("album")
                         where currentYear - int.Parse(album.Element("year").Value) >= olderThanYears
                         select new
                         {
                             Name = album.Element("name").Value,
                             Price = album.Element("price").Value
                         };
            Dictionary<string, decimal> albumPrices = new Dictionary<string, decimal>();
            foreach (var item in albums)
            {
                albumPrices.Add(item.Name, decimal.Parse(item.Price, culture));
            }
            return albumPrices;

        }

        static void Main()
        {
            const string SourceXML = @"..\..\..\catalog.xml";
            const int MinYears = 5;

            //Dictionary<string, decimal> albumPrices = ExtractPricesXPath(SourceXML, MinYears);
            Dictionary<string, decimal> albumPrices = ExtractPricesLINQ(SourceXML, MinYears);

            foreach (var albumPrice in albumPrices)
            {
                Console.WriteLine("{0}: {1}", albumPrice.Key, albumPrice.Value);
            }
        }
    }
}
